package listdemo;

import java.util.Arrays;

public class MyList implements IList{
    public int size ;
    public int [] arr;

    public MyList() {
        this.arr = new int[10];
    }

    @Override
    public void add(int val) {
        if (isFull()){
            grow();
        }
        arr[size] = val;
        size++;
    }
//满了就扩容 单独写一个扩容
    private void grow(){
        arr = Arrays.copyOf(arr,2*arr.length);
    }
    @Override//这里要重写一下
    //不能跳着插入
    public void add(int pos, int val) {
        if(pos < 0 || pos >size){
            throw new MyarrayOutException("下标输错o(╥﹏╥)o");
        }
        if (isFull()){
            grow();
        }
        for (int i = size - 1; i >= pos;i--) {
            arr[i+1] = arr[i];
        }
        arr[pos] = val;
        size++;
    }

/**
 判断是否有这个数*/
    @Override
    public boolean contains(int toFind) {
        for (int i = 0; i < size; i++) {
            if (arr[i] == toFind){
                return true;
            }
        }
        return false;
    }

    @Override
    public int indexOf(int val) {
        for (int i = 0; i < size; i++) {
            if (arr[i] == val){
                return i;
            }
        }
        return -1;
    }

    @Override
    public int get(int pos) {
        if(pos < 0 || pos > size -1){
            throw new MyarrayOutException("下标输错o(╥﹏╥)o");
        }else return arr[pos];
    }

    @Override
    public void set(int pos, int val) {
        if(pos < 0 || pos > size -1){
            throw new MyarrayOutException("下标输错o(╥﹏╥)o");
        }else {
            arr[pos] = val;
        }
    }

    @Override
    public void remove(int toRemove) {
        int index = indexOf(toRemove);
        if (index < 0){
            throw new MyarrayOutException("没有这个数");
        }
        for(int i = index; i < size - 1 ; i ++){
            arr[i] = arr[i+1];
        }
        /*for (int i = 0; i < size; i++) {
            if (arr[i] == toRemove){
                for(int j = i ; j < size;j++){
                    arr[j] = arr[j+1];
                }
            }
        }*/
        size--;
    }

    @Override
    public int size() {
        return size;
    }

    @Override
    public void clear() {
        arr = new int[0];
        for (int i = 0;i<size;i++){
            arr[i] = 0;
        }
        size = 0;
    }

    @Override
    public void dispaly() {
        for (int i = 0; i < size; i++){
            System.out.print(arr[i] + " ");
        }
    }
    public boolean isFull(){
        if (arr.length == size){
            return true;
        }
        return false ;
        //如果等于的话就是TRUE 直接 return arr.length == size;
    }

    @Override
    public String toString() {
        return "MyList{" +
                "size=" + size +
                ", arr=" + Arrays.toString(arr) +
                '}';
    }
}
